package com.genesis.yunnanji.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.activity.WebActivity;
import com.genesis.yunnanji.adapter.NewsHomeAdapter2;
import com.genesis.yunnanji.bean.HomePageListBean;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.utils.GenesisUtils;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.Call;


public class NewsHome extends Fragment {


    private View view;
    private GenesisUtils genesisUtils;
    private RecyclerView newList;
    private TwinklingRefreshLayout refreshLayout;
    private int page = 0;
    private Intent intent;
    private Banner banner;
    private Gson gson = new Gson();


    public static NewsHome newInstance(String param) {
        NewsHome obj = new NewsHome();
        Bundle bundle = new Bundle();
        bundle.putString("args1", param);
        obj.setArguments(bundle);
        return obj;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = this.getActivity().getLayoutInflater().inflate(R.layout.fragment_newshome, null);
            newList = (RecyclerView) view.findViewById(R.id.rv_newshome2);
            refreshLayout = (TwinklingRefreshLayout) view.findViewById(R.id.bga_newshome_refresh);
            genesisUtils = GenesisUtils.getIntance();
            getNewsData(refreshLayout, false);
            initView();
        } else {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
        }

        return view;
    }

    protected void initView() {

        newList.setLayoutManager(new LinearLayoutManager(getActivity()));
        newList.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.divider)).build());
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                page = 0;
                arrayBanner.clear();
                arrayNews.clear();
                getNewsData(refreshLayout, true);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                page += 1;
                getNewsData(refreshLayout,false);
            }
        });

    }

    View headerView;

    private View getHeaderView() {

        List<String> bannerImages;
        headerView = LayoutInflater.from(getContext()).inflate(R.layout.layout_headerview, (ViewGroup) newList.getParent(), false);
        banner = (Banner) headerView.findViewById(R.id.banner);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra("url", arrayBanner.get(position).getTarget_link());
                startActivity(intent);
            }
        });
        bannerImages = new ArrayList<>();

        if (homePageListBean.getResult().getBanner().size() < 0) {
            banner.setVisibility(View.GONE);
        } else {
            for (int i = 0; i < homePageListBean.getResult().getBanner().size(); i++) {
                bannerImages.add(homePageListBean.getResult().getBanner().get(i).getAdvert_img());
            }
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            banner.setImageLoader(new GlideImageLoader());
            banner.setIndicatorGravity(BannerConfig.RIGHT);
            banner.isAutoPlay(true);
            banner.setDelayTime(5000);
            banner.setImages(bannerImages);
            banner.start();
        }

        return headerView;
    }

    static class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            ImageOptions imageOptions = new ImageOptions.Builder().setImageScaleType(ImageView.ScaleType.FIT_XY).build();
            x.image().bind(imageView, GenesisApiConfig.PIC_HOST + (String) path, imageOptions);
        }

    }

    HomePageListBean homePageListBean;
    NewsHomeAdapter2 newsHomeAdapter2;
    List<HomePageListBean.ResultBean.ListBean> arrayNews = new ArrayList<>();
    List<HomePageListBean.ResultBean.BannerBean> arrayBanner = new ArrayList<>();

    private void getNewsData(final TwinklingRefreshLayout refreshLayout, final boolean isRefresh) {

        OkHttpUtils.get()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.HOME_PAGE)
                .addParams("p", page + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        refreshLayout.finishRefreshing();
                        refreshLayout.finishLoadmore();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        refreshLayout.finishRefreshing();
                        refreshLayout.finishLoadmore();
                        homePageListBean = gson.fromJson(response, HomePageListBean.class);
                        if (homePageListBean.getStatus() == 200) {
                            for (int i = 0; i < homePageListBean.getResult().getList().size(); i++) {
                                arrayNews.add(homePageListBean.getResult().getList().get(i));
                            }
                            if (page == 0) {
                                arrayBanner = homePageListBean.getResult().getBanner();
                                newsHomeAdapter2 = new NewsHomeAdapter2(arrayNews, getActivity(), true);
                                newsHomeAdapter2.addHeaderView(getHeaderView());
                                newList.setAdapter(newsHomeAdapter2);

                                newsHomeAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        intent = new Intent(getActivity(), WebActivity.class);
                                        if (genesisUtils.isLogin()) {
                                            intent.putExtra("url", arrayNews.get(position).getTaget_link() + GenesisApiConfig.FROM_APP + GenesisApiConfig.APP_TOKEN + genesisUtils.getAppToken());
                                        } else {
                                            intent.putExtra("url", arrayNews.get(position).getTaget_link() + GenesisApiConfig.FROM_APP);

                                        }
                                        startActivity(intent);
                                    }
                                });
                            } else {
                            }
                        } else {
                            Toasty.info(getActivity(), homePageListBean.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }
                });

    }


}
